﻿using AntDesign;
using Flurl;
using Flurl.Http;

namespace HZY.Admin.Blazor.Client.Pages.Login;

public partial class Login
{
    public string UserName { get; set; }

    public string Password { get; set; }

    public bool Loading { get; set; } = false;

    [Inject]
    public NavigationManager NavigationManager { get; set; } = null!;

    [Inject]
    public IJSRuntime JSRuntime { get; set; } = null!;

    [Inject] public HttpClient? HttpClient { get; set; }

    [Inject] public IMessageService Message { get; set; } = null!;

    public async Task CheckAsync()
    {
        Loading = true;
        StateHasChanged();

        try
        {
            var result = await (await $"http://localhost:5500/api/v1/identity/Account/Login".PostJsonAsync(new
            {
                UserName,
                UserPassword = Password
            })).GetJsonAsync<R<LoginResultDto>>();

            var data = result.Data;
            if (result.Code != 200)
            {
                await Message.Error(result.Message);
                return;
            }

            string? token = result.Data?.Token;
            if (string.IsNullOrWhiteSpace(token))
            {
                await Message.Error("错误 token");
                return;
            }

            await JSRuntime.SetLocalStorageItemAsync("token", token);
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            Loading = false;
            StateHasChanged();

        }

        //var result = HttpClient!.PostAsJsonAsync($"/api/v1/identity/Account/Login", new
        //{
        //    UserName,
        //    Password
        //}).Result;

        NavigationManager.NavigateTo("/");
    }

}

public class LoginResultDto
{


    public string? Token { get; set; }

    public string? TokenType { get; set; }

}
